package com.hc.ureport.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Collection;

@ApiModel(value = "HttpResultModel", description = "Http返回结果")
@Data
@Accessors(chain = true)
public class HttpResultModel<T> {

    @ApiModelProperty("状态码：200-成功, 其余失败")
    private int code = 0;

    @ApiModelProperty("错误信息")
    private String msg = "";

    @ApiModelProperty("总数")
    private Integer total = 0;

    @ApiModelProperty("发送时间戳")
    private long sendTime;  //UTC 时间戳

    @ApiModelProperty("数据")
    private T data;

    /**
     * 返回JSON结果
     */
    public static <T> HttpResultModel<T> sendResult(T result) {
        int total = 0;
        if (result != null) {
            if (result instanceof Collection) {
                total = ((Collection<?>) result).size();
            } else {
                total = 1;
            }
        }

        return sendResult(200, result, total);
    }

    /**
     * 返回JSON结果
     */
    public static <T> HttpResultModel<T> sendResult(int code, T result) {
        int total = 0;
        if (result != null) {
            if (result instanceof Collection) {
                total = ((Collection<?>) result).size();
            } else {
                total = 1;
            }
        }

        return sendResult(code, result, total);
    }

    /**
     * 返回JSON结果
     *
     * @param total 总数
     */
    public static <T> HttpResultModel<T> sendResult(int code, T result, Integer total) {
        HttpResultModel<T> resultModel = new HttpResultModel<>();
        resultModel.setCode(code);
        resultModel.setSendTime(System.currentTimeMillis());
        resultModel.setTotal(total);
        resultModel.setData(result);

        return resultModel;
    }

    /**
     * 返回JSON错误信息
     */
    public static <T> HttpResultModel<T> sendError(int code, String error) {
        HttpResultModel<T> resultModel = new HttpResultModel<>();
        resultModel.setSendTime(System.currentTimeMillis());
        resultModel.setCode(code);
        resultModel.setMsg(error);
        return resultModel;
    }

}
